﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsAPI.Windows
{
    [Serializable]
    public class SystemMenu
    {
        /* ------------------------------------------------------------------------------------------ */

        /// <summary>Создать экземпляр меню по дескриптору окна</summary>
        /// <param name="window">Интерфейс окна</param>
        /// <returns>СИстемное меню окна</returns>
        public static SystemMenu Create(IWin32Window window)
        {
            var hWnd = User32.SystemMenu.GetSystemMenu(window.Handle);
            if(hWnd == IntPtr.Zero)
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            return new SystemMenu(hWnd);
        }

        /* ------------------------------------------------------------------------------------------ */

        private readonly IntPtr f_Handle;

        /* ------------------------------------------------------------------------------------------ */

        /// <summary>Дескриптор меню окна</summary>
        public IntPtr Handle { get { return f_Handle; } }

        /// <summary>Число пинктов меню</summary>
        public int ItemCount
        {
            get
            {
                var lv_Result = User32.SystemMenu.GetMenuItemCount(f_Handle);
                if(lv_Result < 0)
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                return lv_Result;
            }
        }

        /* ------------------------------------------------------------------------------------------ */

        /// <summary>Системное меню по дескриптору</summary>
        /// <param name="Handle"></param>
        public SystemMenu(IntPtr Handle) { f_Handle = Handle; }

        /* ------------------------------------------------------------------------------------------ */

        public bool InsertMenu(User32.SystemMenu.PositionFlags PosF, User32.SystemMenu.Flags Flags, int ID, string Text)
        {
            return User32.SystemMenu.InsertMenu(f_Handle, PosF, Flags, ID, Text);
        }

        public bool InsertMenu(int Pos, User32.SystemMenu.Flags Flags, int ID, string Text)
        {
            return User32.SystemMenu.InsertMenu(f_Handle, Pos, Flags, ID, Text);
        }

        /* ------------------------------------------------------------------------------------------ */
    }
}
